<template>
  <c-back-wrap :loading="loading" go-page="经销商档案新建管理" current-page="审核">
    <QupFormContainer :column="1">
      <el-form ref="form" :model="formData" :rules="formRules" label-width="110px">
        <el-form-item prop="fileReviewResult" label="审批结果">
          <c-dict-select v-model="formData.fileReviewResult" dict-type-code="REVIEW_RESULT" clearable placeholder="审批结果" />
        </el-form-item>
        <el-form-item v-if="[2, '2'].includes(formData.fileReviewResult)" prop="assistToHandleAccount" label="协办用户" :span="24/4">
          <c-common-search-qup-person v-model="formData.assistToHandleAccount" :label.sync="formData.assistToHandleName" multiple placeholder="协办用户" />
        </el-form-item>
        <el-form-item prop="fileReviewAdvice" label="审批意见">
          <el-input v-model="formData.fileReviewAdvice" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows: 3}" placeholder="审批意见" clearable />
        </el-form-item>
      </el-form>
    </QupFormContainer>
    <QupList :column="3" sep="：" default-value="" label-position="right" label-width="130">
      <QupListItem key="officeName" label="办事处" :value="detail.officeName" />
      <QupListItem key="officeTypeName" label="办事处类别" :value="detail.officeTypeName" />
      <QupListItem key="personName" label="办事处负责人" :value="detail.personName" />
      <QupListItem key="receiveManagerCode" label="接收客户经理" :value="detail.receiveManagerCode" />
      <QupListItem key="receiveManagerName" label="接收客户经理名称" :value="detail.receiveManagerName" />
      <QupListItem key="receiveManagerTypeName" label="接收客户经理类型" :value="detail.receiveManagerTypeName" />
      <QupListItem key="receiveManagerTel" label="接收客户经理电话" :value="detail.receiveManagerTel" />
    </QupList>
    <c-title title="经销商基本信息">
      <QupList :column="3" sep="：" default-value="" label-position="right" label-width="130">
        <QupListItem v-if="editable" label-width="0" :span="24">
          <el-form ref="customerForm" :model="customerFormData" :rules="formRules" label-width="130px">
            <el-form-item label="客户编码" prop="customerCode">
              <!-- 客户编码选择后，经销商系统名称、经销商姓名、经销商身份证号、
              经销商身份证详细地址、合作起始日期根据客户编码获取主数据值后自动更新； -->
              <c-common-search-customer
                v-model="customerFormData.customerCode"
                :label.sync="customerFormData.customerName"
                :format-label="v=>v.code"
                :legal-person_res.sync="customerFormData.legalPerson"
                :credential-no_res.sync="customerFormData.credentialNo"
                :cooperate-start_res.sync="customerFormData.cooperateStart"
                :customer-abbr_res.sync="customerFormData.disAddr"
                :business-type-name_res.sync="customerFormData.businessTypeName"
                :business-type-code_res.sync="customerFormData.businessTypeCode"
                :office-code="detail.officeCode"
                style="width:240px"
                @change="handleCustomerChange"
              />
            </el-form-item>
            <!-- <el-form-item label="客户编码" prop="customerName">
              <span>{{ customerFormData.customerName }}</span>
            </el-form-item> -->
          </el-form>
        </QupListItem>
        <QupListItem key="customerName" label="经销商系统名称" :value="changeCustomerFormData.customerName" />
        <QupListItem key="legalPerson" label="经销商姓名" :value="changeCustomerFormData.legalPerson" />
        <QupListItem key="credentialNo" label="经销商身份证号" :value="changeCustomerFormData.credentialNo" />
        <!-- <QupListItem key="disAddr" label="身份证详细地址" :value="changeCustomerFormData.disAddr" /> -->
        <QupListItem key="cooperateStart" label="合作起始日期" :value="$trimHMS(changeCustomerFormData.cooperateStart)" />
        <QupListItem key="businessTypeName" label="客户业务类型" :value="changeCustomerFormData.businessTypeName" />
        <QupListItem label="身份证正面图片" :span="24">
          <c-file-list v-if="finishedDetail" v-model="customerFormData.ACCESS050" :uploadable="editable" :editable="editable" direct-del :model-id="id" :limit="1" view-type="list" type-code="ACCESS050" />
          <!-- <c-file-list :uploadable="false" v-if="finishedDetail" :model-id="id" view-type="list" type-code="ACCESS050" /> -->
        </QupListItem>
        <QupListItem label="身份证反面图片" :span="24">
          <c-file-list v-if="finishedDetail" v-model="customerFormData.ACCESS051" :uploadable="editable" :editable="editable" direct-del :model-id="id" :limit="1" view-type="list" type-code="ACCESS051" />
          <!-- <c-file-list :uploadable="false" :editable="false" v-if="finishedDetail" :model-id="id" view-type="list" type-code="ACCESS051" /> -->
        </QupListItem>
        <QupListItem label="资金安全告知函" :span="24">
          <c-file-list v-if="finishedDetail" v-model="customerFormData.ACCESS052" :uploadable="editable" :editable="editable" direct-del :model-id="id" :limit="1" view-type="list" type-code="ACCESS052" />
          <!-- <c-file-list :uploadable="false" :editable="false" v-if="finishedDetail" :model-id="id" view-type="list" type-code="ACCESS052" /> -->
        </QupListItem>
        <QupListItem label="签字签章函" :span="24">
          <c-file-list v-if="finishedDetail" v-model="customerFormData.ACCESS053" :uploadable="editable" :editable="editable" direct-del :model-id="id" :limit="1" view-type="list" type-code="ACCESS053" />
          <!-- <c-file-list :uploadable="false" :editable="false" v-if="finishedDetail" :model-id="id" view-type="list" type-code="ACCESS053" /> -->
        </QupListItem>
        <QupListItem label="收货地址确认单" :span="24">
          <c-file-list v-if="finishedDetail" v-model="customerFormData.ACCESS054" :uploadable="editable" :editable="editable" direct-del :model-id="id" :limit="1" view-type="list" type-code="ACCESS054" />
          <!-- <c-file-list :uploadable="false" :editable="false" v-if="finishedDetail" :model-id="id" view-type="list" type-code="ACCESS054" /> -->
        </QupListItem>
        <QupListItem key="isDeposit" label="是否缴纳保证金" :value="detail.isDeposit" dict-type-code="BOOLEANS" :prop-enum="{domainCode:'marketing',appCode:'slm'}" />
        <QupListItem v-if="[1, '1'].includes(detail.isDeposit)" key="depositDate" label="保证金缴纳日期" :value="$trimHMS(detail.depositDate)" />
        <QupListItem key="finishedDeposit" label="成品保证金金额(元)" :value="`${detail.finishedDeposit || 0}`" />
        <QupListItem key="customizedDeposit" label="定制保证金金额(元)" :value="`${detail.customizedDeposit || 0}`" />
        <QupListItem key="cupboardDeposit" label="橱柜保证金金额(元)" :value="`${detail.cupboardDeposit || 0}`" />
        <QupListItem key="bathroomDeposit" label="卫浴保证金金额(元)" :value="`${detail.bathroomDeposit || 0}`" />
      </QupList>
    </c-title>
    <c-title title="经销商-收货地址">
      <AddrTable title="经销商-收货地址" :table-data="detail.addressDTOS" type="view" :customer-code="changeCustomerFormData.customerCode" :show-edit-addr-code="editable" />
    </c-title>
    <c-title title="经销商-联系人">
      <ContactsTable title="经销商-联系人" :table-data="customerContactsData" type="view" />
    </c-title>
    <c-title>
      <div slot="title" style="display:flex;align-items:center;">
        <span class="title" style="margin-right: 5px">是否合伙经营</span>
        <span>{{ [1,'1'].includes(isPartnership)?'是':'否' }}</span>
      </div>
      <PartnershipTable v-show="[1,'1'].includes(isPartnership)" title="合伙经营" :table-data="partnerData" />
    </c-title>
    <c-title title="交接信息">
      <QupList :column="1" sep="：" default-value="" label-position="right" label-width="130">
        <QupListItem key="isMarketConnect" label="是否经销商交接" :value="detail.isMarketConnect" dict-type-code="BOOLEANS" :prop-enum="{domainCode:'marketing',appCode:'slm'}" />
        <template v-if="[1,'1'].includes(detail.isMarketConnect)">
          <QupListItem label-width="0" :span="24">
            <!-- <DistributionTable
              title="交接信息" :
              table-data="handoverDTOS"
               type="view"
               :customer-code="changeCustomerFormData.customerCode"
               :editable-column="['toAccountCode']"
               :hidden-column="['fromShopCode', 'fromShopName']" /> -->
            <DistributionTable
              ref="distributionTable"
              title="交接信息"
              :table-data="handoverDTOS"
              :customer-code="changeCustomerFormData.customerCode"
              :office-code="detail.officeCode"
              :hidden-column="['fromShopCode', 'fromShopName']"
              :type="editable?'edit':'view'"
              filter-q-y-q-j-k-u
              is-audit
            />
          </QupListItem>
          <QupListItem label="经销商交接证明" :span="24">
            <c-file-list v-if="finishedDetail" v-model="customerFormData.ACCESS058" :uploadable="editable" :editable="editable" direct-del :model-id="id" view-type="list" type-code="ACCESS058" />
            <!-- <c-file-list :uploadable="false" :editable="false" v-if="finishedDetail" :model-id="id" view-type="list" type-code="ACCESS058" /> -->
          </QupListItem>
          <QupListItem label="经销商关系证明" :span="24">
            <c-file-list v-if="finishedDetail" v-model="customerFormData.ACCESS059" :uploadable="editable" :editable="editable" direct-del :model-id="id" view-type="list" type-code="ACCESS059" />
            <!-- <c-file-list :uploadable="false" :editable="false" v-if="finishedDetail" :model-id="id" view-type="list" type-code="ACCESS059" /> -->
          </QupListItem>
          <QupListItem label="交接双方现场签订照片" label-width="160px" :span="24">
            <c-file-list v-if="finishedDetail" v-model="customerFormData.ACCESS111" :uploadable="editable" :editable="editable" direct-del :model-id="id" view-type="list" type-code="ACCESS111" />
          </QupListItem>
          <QupListItem v-if="finishedDetail" prop="1" label="交接双方现场签订照片模板下载" label-width="190px" :span="24">
            <div class="template-down" @click.stop="handleDownTemplate(ACCESS111.id)">
              <span>交接双方现场签订照片模板下载</span>
              <i class="el-icon-download" />
            </div>
          </QupListItem>
        </template>
      </QupList>
    </c-title>
    <c-title title="门店基本信息">
      <QupList :column="1" label-width="140">
        <QupListItem v-if="hasIsMarketConnect" key="isTakeOverTheOriginalStore" label="是否接管原商家门店" dict-type-code="BOOLEANS" :prop-enum="{domainCode:'marketing',appCode:'slm'}" :value="detail.isTakeOverTheOriginalStore" />
        <QupListItem v-if="isTakeOver" label="" label-width="0">
          <c-title title="新增门店信息">
            <ShopTable v-if="editable" ref="shopTable" key="shopTable" :table-data="customerShopData" is-audit :customer-code="customerFormData.customerCode" @on-takeover-change="handleOnTakeoverChange" @onCodeChange="handleOnCodeChange" />
            <ShopTable v-else :table-data="customerShopDataM" :is-edit="false" />
          </c-title>
          <c-title title="门店联系人">
            <ShopContactTable v-if="editable" ref="shopContactTable" key="shopContactTable" :table-data="shopContactsDataM" :shop-data="customerShopData" is-audit :customer-code="customerFormData.customerCode" />
            <ShopContactTable v-else :table-data="shopContactDTOSM" :shop-data="customerShopDataM" :is-edit="false" />
          </c-title>
        </QupListItem>
      </QupList>
      <QupList v-if="![1, '1'].includes(detail.isTakeOverTheOriginalStore)" :column="3" sep="：" default-value="" label-position="right" label-width="140">
        <QupListItem v-if="editable" key="code" :value="detail.code" label-width="0" :span="24">
          <el-form ref="shopForm" :model="shopFormData" :rules="formRules" label-width="130px">
            <el-form-item label="门店" prop="code">
              <c-common-search-shop-by-customer
                v-model="shopFormData.code"
                :label.sync="shopFormData.name"
                :format-label="v=>v.code"
                :customer-code="changeCustomerFormData.customerCode"
                :disabled="!changeCustomerFormData.customerCode"
                :depend-on-observe="changeCustomerFormData.customerCode"
                start-observe
                style="width:240px"
                @change="handleShopChange"
              />
            </el-form-item>
            <!-- <el-form-item label="门店编码" prop="name">
              <span>{{ shopFormData.name }}</span>
            </el-form-item> -->
          </el-form>
        </QupListItem>
        <QupListItem key="businessTypeName" label="门店经营业务类型" :value="changeShopFormData.businessTypeName" />
        <QupListItem key="name" label="门店名称" :value="changeShopFormData.name" />
        <QupListItem key="shopClassifyName" label="门店类型" :value="changeShopFormData.shopClassifyName" />
        <QupListItem key="countryName" label="国别" :value="changeShopFormData.countryName" />
        <QupListItem key="provinceName" label="省份" :value="changeShopFormData.provinceName" />
        <QupListItem key="cityName" label="城市" :value="changeShopFormData.cityName" />
        <QupListItem key="countyName" label="区/县" :value="changeShopFormData.countyName" />
        <QupListItem key="townName" label="街道/乡镇" :value="changeShopFormData.townName" />
        <QupListItem key="shopAddr" label="详细地址" :value="changeShopFormData.shopAddr" :span="24" />
        <QupListItem key="floor" label="所在楼层" :value="changeShopFormData.floor" />
        <QupListItem key="cityLevelName" label="城市级别" :value="changeShopFormData.cityLevelName" />
        <QupListItem key="marketLevelName" label="市场层级" :value="changeShopFormData.marketLevelName" />
        <QupListItem key="shopInfoPhone" label="门店咨询电话" :value="changeShopFormData.shopInfoPhone" />
        <QupListItem key="shopServPhone" label="售后电话" :value="changeShopFormData.shopServPhone" />
        <QupListItem key="outpicArea" label="出图总面积" :value="`${changeShopFormData.outpicArea || 0}㎡`" />
        <QupListItem key="isDecorationDoorHead" label="是否装修门头" :value="changeShopFormData.isDecorationDoorHead" dict-type-code="BOOLEANS" :prop-enum="{domainCode:'marketing',appCode:'slm'}" />
        <!-- <QupListItem key="doorHeadArea" label="门头面积" :value="`${changeShopFormData.doorHeadArea || 0}㎡`" /> -->
        <QupListItem label="营业执照图片" :span="24">
          <c-file-list v-model="shopFormData.ACCESS055" :uploadable="editable" :editable="editable" direct-del :model-id="shopDTO.id" view-type="list" type-code="ACCESS055" />
          <!-- <c-file-list :uploadable="false" :editable="false" :model-id="shopDTO.id" view-type="list" type-code="ACCESS055" /> -->
        </QupListItem>
        <QupListItem label="专卖店特许经营合同图片" :span="24" label-width="150">
          <c-file-list v-model="shopFormData.ACCESS056" :uploadable="editable" :editable="editable" direct-del :model-id="shopDTO.id" view-type="list" type-code="ACCESS056" />
          <!-- <c-file-list :uploadable="false" :editable="false" :model-id="shopDTO.id" view-type="list" type-code="ACCESS056" /> -->
        </QupListItem>
        <QupListItem key="endProductArea" label="成品面积" :value="`${shopDTO.endProductArea || 0}㎡`" />
        <QupListItem key="fullHouseArea" label="全屋定制面积" :value="`${shopDTO.fullHouseArea || 0}㎡`" />
        <QupListItem key="cabinetArea" label="整体橱柜面积" :value="`${shopDTO.cabinetArea || 0}㎡`" />
        <QupListItem key="bathroomArea" label="卫浴面积" :value="`${shopDTO.bathroomArea || 0}㎡`" />
        <QupListItem key="modelRoomArea" label="样板间面积" :value="`${shopDTO.modelRoomArea || 0}㎡`" />
        <QupListItem key="curtainArea" label="窗帘面积" :value="`${shopDTO.curtainArea || 0}㎡`" />
        <QupListItem key="cabinetSuite" label="橱柜套数" :value="shopDTO.cabinetSuite" />
        <QupListItem key="bathroomSuite" label="卫浴套数" :value="shopDTO.bathroomSuite" />
        <QupListItem key="totalArea" label="单店总面积" :value="`${shopDTO.totalArea || 0}㎡`" />
        <QupListItem key="headTypeName" label="门头类型" :value="shopDTO.headTypeName" />
        <QupListItem key="doorHeadArea" label="门头面积" :value="`${shopDTO.doorHeadArea || 0}㎡`" />
        <QupListItem key="lintelArea" label="门楣面积" :value="`${shopDTO.lintelArea || 0}㎡`" />
      </QupList>
    </c-title>
    <template v-if="!isTakeOver">
      <c-title title="门店联系人">
        <ContactsTable title="门店联系人" :table-data="shopContactsData" />
      </c-title>
      <c-title title="门店报图情况">
        <QupList :column="1" sep="：" default-value="" label-position="right" label-width="130">
          <QupListItem key="isReportPic" label="是否报图" :value="shopDTO.isReportPic" :span="24" dict-type-code="BOOLEANS" :prop-enum="{domainCode:'marketing',appCode:'slm'}" />
          <QupListItem v-if="shopDTO && shopDTO.id" label="特殊建档附件" :span="24">
            <c-file-list v-model="shopFormData.ACCESS057" :uploadable="editable" :editable="editable" direct-del tip="如未报图/未交保证金等情况，业务请示申请审核通过的流程附件" :model-id="shopDTO.id" view-type="list" type-code="ACCESS057" />
            <!-- <c-file-list :uploadable="false" :editable="false" :model-id="shopDTO.id" view-type="list" type-code="ACCESS057" /> -->
          </QupListItem>
        </QupList>
      </c-title>
    </template>
    <c-title title="流程审批信息">
      <QupList :column="3" sep="：" default-value="" label-position="right" label-width="130">
        <QupListItem :value="detail.createBy" label="申请人" />
        <QupListItem :value="detail.createTime" label="申请时间" />
        <QupListItem :value="detail.applyNo" label="BPM单号" />
        <QupListItem label="客户经理档案提报原始表单" label-width="180px" :span="24">
          <c-file-list :uploadable="false" :editable="false" :model-id="id" view-type="list" type-code="ACCESS080" />
        </QupListItem>
        <!-- <QupListItem key="officeReviewResult" label="办事处审批结果" :value="detail.officeReviewResult" dict-type-code="REVIEW_RESULT" :prop-enum="{domainCode:'marketing',appCode:'slm'}" /> -->
        <!-- <QupListItem :value="detail.officeReviewTime" label="办事处审批结束时间" /> -->
        <!-- <QupListItem :value="detail.officeReviewAdvice" label="办事处审批意见" :span="24" /> -->
        <!-- <QupListItem :value="detail.officeAccountingReviewAdvice" label="办事处会计处理意见" :span="24" /> -->
        <!-- <QupListItem key="fileReviewResult" label="档案科审批结果" :value="detail.fileReviewResult" dict-type-code="REVIEW_RESULT" :prop-enum="{domainCode:'marketing',appCode:'slm'}" />
        <QupListItem :value="detail.fileReviewTime" label="档案科审批结束时间" />
        <QupListItem :value="detail.fileReviewAdvice" label="档案科审批意见" :span="24" />
        <QupListItem :value="detail.fileReviewAdvice" label="系统管理员开通TOP系统账号节点处理意见" label-width="250" :span="24" /> -->
      </QupList>
      <Options :data="detail.opinionDTOS" />
    </c-title>

    <div class="btn-center">
      <c-button type="default" @click="handleCancel">取消</c-button>
      <c-button type="primary" @click="handleConfirm">确认</c-button>
    </div>
  </c-back-wrap>
</template>
<script>
import { archiveDetail, auditInfoCreate } from '@/api/channelTask2/newArchive'
import AddrTable from '../../components/AddrTable'
import ContactsTable from '../../components/ContactsTable'
import PartnershipTable from '../../components/PartnershipTable'
import DistributionTable from '../../components/DistributionTable'
import Options from '../../components/Options'
import { contactByShop, contactByCustomer, ctmCustomerPartner } from '@/api/channelTask2/change'
import { downTemplate, getTemplateConfig } from '@/api/channelTask2/change'
import { getShopByCustomerCode, getShopContactByShopCode } from '@/api/channelTask2/newArchive'
import ShopTable from './ShopTable'
import ShopContactTable from './ShopContactTable'

export default {
  name: 'Audit',
  components: {
    AddrTable,
    ContactsTable,
    PartnershipTable,
    DistributionTable,
    Options,
    ShopTable,
    ShopContactTable
  },
  props: {
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      detail: {
        shopDTOS: []
      },
      loading: false,
      formData: {
        fileReviewResult: '',
        fileReviewAdvice: '',
        assistToHandleAccount: [],
        assistToHandleName: []
      },
      customerFormData: {
        customerCode: '',
        customerName: '',
        legalPerson: '',
        credentialNo: '',
        disAddr: '',
        cooperateStart: '',
        businessTypeCode: '',
        businessTypeName: '',
        // 附件
        ACCESS050: [],
        ACCESS051: [],
        ACCESS052: [],
        ACCESS053: [],
        ACCESS054: [],
        // 交接
        ACCESS058: [],
        ACCESS059: [],
        ACCESS111: []
      },
      shopFormData: {
        businessType: '',
        businessTypeName: '',
        code: '',
        name: '',
        shopClassify: '',
        shopClassifyName: '',
        countryCode: '', //	国家
        countryName: '',
        province: '', //	省份
        provinceName: '',
        city: '', //	城市
        cityName: '',
        county: '', //	区县
        countyName: '',
        town: '', //	街道
        townName: '',
        shopAddr: '',
        floor: '',
        cityLevel: '', //	城市级别
        cityLevelName: '',
        marketLevelCode: '', //	市场层级
        marketLevelName: '',
        shopInfoPhone: '',
        shopServPhone: '',
        outpicArea: '',
        isDecorationDoorHead: '',
        doorHeadArea: '',
        // 附件
        ACCESS055: [],
        ACCESS056: [],
        ACCESS057: []
      },
      addrTableData: [],
      contactsTableData: [],
      partnershipTableData: [],
      shopContactsTableData: [],
      handoverDTOS: [],
      // mdm客户联系人
      mdmCustomerContactsData: [],
      // mdm门店联系人
      mdmShopContactsData: [],
      // mdm合伙人信息
      mdmPartnerData: [],
      editIsPartnership: 0, // 是否合伙经营
      ACCESS111: {},
      customerShopData: [],
      shopContactsDataM: []
    }
  },
  computed: {
    formRules() {
      return {
        fileReviewResult: [{ required: true, message: '请选择审批结果', trigger: 'change' }],
        assistToHandleAccount: [{ required: true, validator: (r, v, c) => {
          if (!v || v.length === 0) {
            c(new Error('请选择协办用户'))
          } else {
            c()
          }
        }, trigger: 'change' }],
        fileReviewAdvice: [{ required: true, message: '请输入审批意见', trigger: 'change' }],
        // 客户编码
        customerCode: [{ required: this.editable, message: '请选择客户', trigger: 'change' }],
        // 门店编码
        code: [{ required: this.editable, message: '请选择门店', trigger: 'change' }]
      }
    },
    editable() {
      return [1, '1'].includes(this.formData.fileReviewResult)
    },
    shopDTO() {
      return this.detail.shopDTOS[0] || {}
    },
    changeCustomerFormData() {
      return this.editable && !!this.customerFormData.customerCode ? this.customerFormData : this.detail
    },
    changeShopFormData() {
      return this.editable && !!this.shopFormData.code ? this.shopFormData : this.shopDTO
    },
    finishedDetail() {
      return this.detail && Object.keys(this.detail).length > 0
    },
    hasIsTransferSales() {
      return this.handoverDTOS.some(e => [1, '1'].includes(e.isTransferSales))
    },
    // 门店联系人
    shopContactsData() {
      return (this.editable ? this.mdmShopContactsData : this.detail.contactDTOS || []).filter(e => [3, '3'].includes(e.contactScope))
    },
    customerContactsData() {
      return (this.editable ? this.mdmCustomerContactsData : this.detail.contactDTOS || []).filter(e => [1, '1'].includes(e.contactScope))
    },
    partnerData() {
      return this.editable ? this.mdmPartnerData : this.detail.partnerDTOS || []
    },
    isPartnership() {
      return this.editable ? this.editIsPartnership : this.detail.isPartnership
    },
    hasIsMarketConnect() {
      return [1, '1'].includes(this.detail.isMarketConnect)
    },
    // 是否接管
    isTakeOver() {
      return this.hasIsMarketConnect && [1, '1'].includes(this.detail.isTakeOverTheOriginalStore)
    },
    customerShopDataM() {
      return this.detail.shopDTOS || []
    },
    shopContactDTOSM() {
      return (this.detail.contactDTOS || []).filter(e => [3, '3'].includes(e.contactScope))
    }
  },
  watch: {
    editable: {
      handler(v) {
        const d = this.$deepClone(this.detail)
        this.syncShopBusinessId()
        this.shopContactsDataM = (d.contactDTOS || []).filter(e => [3, '3'].includes(e.contactScope))
      }
    }
  },
  created() {
    this.getDetailData()
    this.templateConfig()
  },
  methods: {
    getDetailData() {
      this.loading = true
      return archiveDetail(this.id).then(res => {
        this.detail = res.data
        this.handoverDTOS = JSON.parse(JSON.stringify(res.data.handoverDTOS || []))
        this.initFormData()
      }).finally(() => {
        this.loading = false
      })
    },
    initFormData() {
      Object.entries(this.customerFormData).forEach(([k, v]) => {
        this.$set(this.customerFormData, k, this.detail[k] !== undefined ? this.detail[k] : v)
      })
      const isTakeOver = [1, '1'].includes(this.detail.isMarketConnect) && [1, '1'].includes(this.detail.isTakeOverTheOriginalStore)
      if (!isTakeOver) {
        const shopDTO = this.detail.shopDTOS[0] || {}
        Object.entries(this.shopFormData).forEach(([k, v]) => {
          this.$set(this.shopFormData, k, shopDTO[k] !== undefined ? shopDTO[k] : v)
        })
      } else {
        this.syncShopBusinessId()
        const d = this.$deepClone(this.detail)
        this.shopContactsDataM = (d.contactDTOS || []).filter(e => [3, '3'].includes(e.contactScope))
      }
    },
    syncShopBusinessId() {
      const d = this.$deepClone(this.detail)
      const codes = (d.handoverDTOS || []).map(e => e.fromCustomerCode)
      codes.length > 0 && getShopByCustomerCode(codes).then(res => {
        // this.customerShopData = res.data
        this.customerShopData = (d.shopDTOS || []).map(e => {
          const t = (res.data || []).find(ee => ee.originalCode === e.originalCode)
          if (t) {
            e.shopBusinessId = t.shopBusinessId
          }
          return e
        })
      })
    },
    handleCancel() {
      this.$pageStack.pop()
    },
    async validate() {
      await this.$refs.form.validate()
      if (this.editable) {
        await this.$refs.customerForm.validate()
        if (!this.isTakeOver) {
          await this.$refs.shopForm.validate()
        }
        const validator = (v, msg) => {
          if (!v || !(v instanceof Array) || v.length === 0) {
            return msg
          }
          return false
        }
        // 校验附件
        const fileRules = {
          ACCESS050: '请上传身份证正面图片',
          ACCESS051: '请上传身份证反面图片',
          ACCESS052: '请上传资金安全告知函',
          ACCESS053: '请上传签字签章函',
          ACCESS054: '请上传收货地址确认单',
          ACCESS055: '请上传营业执照图片',
          ACCESS056: '请上传专卖店特许经营合同图片',
          // ACCESS057: '请上传特殊建档附件',
          ACCESS058: '请上传经销商交接证明',
          ACCESS059: '请上传经销商关系证明',
          ACCESS111: '请上传交接双方现场签订照片'
        }
        const errMsg = []

        'ACCESS050 ACCESS051 ACCESS052 ACCESS053 ACCESS054 ACCESS058 ACCESS059 ACCESS111'.split(' ').forEach(
          k => {
            const msg = fileRules[k]
            if (!msg) return
            if ('ACCESS058 ACCESS111'.includes(k) && ![1, '1'].includes(this.detail.isMarketConnect)) {
              return
            }
            if ('ACCESS059'.includes(k) && !this.hasIsTransferSales) {
              return
            }
            const v = this.customerFormData[k]
            const result = validator(v, msg)
            result && errMsg.push(result)
          }
        )
        // 门店附件
        if (!this.isTakeOver) {
          'ACCESS055 ACCESS056 ACCESS057'.split(' ').forEach(
            k => {
              const msg = fileRules[k]
              if (!msg) return
              const v = this.shopFormData[k]
              const result = validator(v, msg)
              result && errMsg.push(result)
            }
          )
        }
        // 交接信息
        if ([1, '1'].includes(this.detail.isMarketConnect) && this.handoverDTOS.length === 0) {
          errMsg.push('【交接信息】至少有一条数据!')
        }

        if (this.isTakeOver) {
          await this.$refs.shopTable.validate()
          await this.$refs.shopContactTable.validate()
        }

        if (errMsg.length > 0) {
          this.$message({
            type: 'warning',
            dangerouslyUseHTMLString: true,
            message: `<div>${errMsg.join('<br>')}</div>`
          })
          return Promise.reject(false)
        }

        if ([1, '1'].includes(this.detail.isMarketConnect)) {
          await this.$refs.distributionTable.validate()
        }
        // 校验收货地址
        for (let i = 0; i < this.detail.addressDTOS.length; i++) {
          const t = this.detail.addressDTOS[i]
          if (!t.code) {
            this.$message.warning(`请选择【经销商-收货地址】第${i + 1}行收货地址编码!`)
            return Promise.reject(false)
          }
        }
        for (let i = 0; i < this.handoverDTOS.length; i++) {
          const t = this.handoverDTOS[i]
          if (!t.toAccountCode) {
            this.$message.warning(`请选择【交接信息】第${i + 1}行现业务账号!`)
            return Promise.reject(false)
          }
        }
      }
      return Promise.resolve(true)
    },
    getPostData() {
      const data = this.$deepClone(this.detail)
      Object.assign(data, this.formData)
      data.isPartnership = this.isPartnership
      if ([0, '0'].includes(this.isPartnership)) {
        data.partnerDTOS = []
      }
      if (this.editable) {
        data.contactDTOS = [
          ...(this.isTakeOver ? this.$refs.shopContactTable.getData() : this.shopContactsData),
          ...this.customerContactsData
        ]
        data.addressDTOS.forEach(e => {
          Object.keys(e).forEach(k => {
            if (/^_.+/.test(k)) {
              delete e[k]
            }
          })
        })
        const cfd = this.$deepClone(this.customerFormData)
        data.attachmentDTOS = [
          ...this.$getFiles(cfd.ACCESS050 || []),
          ...this.$getFiles(cfd.ACCESS051 || []),
          ...this.$getFiles(cfd.ACCESS052 || []),
          ...this.$getFiles(cfd.ACCESS053 || []),
          ...this.$getFiles(cfd.ACCESS054 || []),
          ...this.$getFiles(cfd.ACCESS058 || []),
          ...this.$getFiles(cfd.ACCESS059 || []),
          ...this.$getFiles(cfd.ACCESS111 || [])
        ]
        'ACCESS050 ACCESS051 ACCESS052 ACCESS053 ACCESS054 ACCESS058 ACCESS059 ACCESS111'.split(' ').forEach(k => {
          delete cfd[k]
        })
        Object.assign(data, cfd)
        if (!this.isTakeOver) {
          const sfd = this.$deepClone(this.shopFormData)
          sfd.attachmentDTOS = [
            ...this.$getFiles(sfd.ACCESS055 || []),
            ...this.$getFiles(sfd.ACCESS056 || []),
            ...this.$getFiles(sfd.ACCESS057 || [])
          ]
          'ACCESS055 ACCESS056 ACCESS057'.split(' ').forEach(k => {
            delete sfd[k]
          })
          Object.assign(data.shopDTOS[0], sfd)
        } else {
          data.shopDTOS = this.$refs.shopTable.getData()
        }

        data.handoverDTOS = this.$deepClone(this.handoverDTOS)
        data.partnerDTOS = this.$deepClone(this.partnerData)
      }
      delete data.opinionDTOS
      // 处理协办用户
      if (data.assistToHandleAccount instanceof Array) {
        data.assistToHandleAccount = data.assistToHandleAccount.join('，')
        data.assistToHandleName = data.assistToHandleName.join('，')
      }
      return data
    },
    handleConfirm() {
      return this.validate().then(() => {
        return auditInfoCreate(this.getPostData()).then(res => {
          this.$message.success('操作成功!')
          this.$pageStack.pop('onPage')
        })
      })
    },
    handleShopChange(value) {
      if (!value) {
        value = {}
      }
      Object.entries(this.shopFormData).forEach(([k, v]) => {
        if (/^ACCESS/.test(k)) {
          return
        }
        this.$set(this.shopFormData, k, value[k] !== undefined ? value[k] : v)
      })
      if (value.code) {
        contactByShop(value.code).then(res => {
          this.mdmShopContactsData = res.data
        })
      } else {
        this.mdmShopContactsData = []
      }
    },
    handleCustomerChange(value) {
      if (value) {
        contactByCustomer(value.code).then(res => {
          this.mdmCustomerContactsData = res.data
        })
        ctmCustomerPartner(value.code).then(res => {
          this.mdmPartnerData = res.data
          if (this.mdmPartnerData.length > 0) {
            this.editIsPartnership = 1
          } else {
            this.editIsPartnership = 0
          }
        })
      } else {
        this.mdmCustomerContactsData = []
        this.mdmPartnerData = []
        this.editIsPartnership = 0
      }
    },
    handleDownTemplate(id) {
      downTemplate(id)
    },
    templateConfig() {
      getTemplateConfig('ACCESS111').then(res => {
        this.ACCESS111 = res
      })
    },
    // 根据客户编码获取门店
    getCustomerShop(codes) {
      this.customerShopData = []
      if (codes.length <= 0) return
      return getShopByCustomerCode(codes).then(res => {
        this.customerShopData = res.data
      })
    },
    // 根据门店编码获取门店联系人
    getShopContact(shop, id) {
      return getShopContactByShopCode(shop.originalCode).then(res => {
        this.shopContactsDataM.push(...(res.data || []).map(e => {
          e.contactTypeCode = '1'
          e.contactTypeName = '责任人'
          e.isAutoAdd = '0'
          e.isChange = '1'
          e.shopBusinessId = id
          e.address = ''
          e.contactFax = ''
          e.contactId = ''
          e.contactPhone = ''
          e.contactTel = ''
          e.email = ''
          e.name = ''
          e.customerCode = ''
          e.shopCode = ''
          e.shopAddress = shop.shopAddr
          return e
        }))
      })
    },
    handleOnCustomerChange(codes) {
      this.getCustomerShop(codes)
    },
    // handleOfficeChange() {
    //   this.customerShopData = []
    //   this.shopContactsDataM = []
    // },
    handleOnTakeoverChange(v, row) {
      if ([1, '1'].includes(v)) {
        this.getShopContact(row, row.shopBusinessId || row.id)
      } else {
        this.shopContactsDataM = this.shopContactsDataM.filter(e => e.shopBusinessId !== row.shopBusinessId || [1, '1'].includes(e.isAutoAdd))
      }
    },
    handleOnCodeChange(shop, row) {
      const tmp = this.shopContactsDataM.filter(e => e.shopBusinessId !== row.shopBusinessId)
      if (!shop || !shop.code) {
        const c = this.$deepClone(this.shopContactDTOSM).filter(e => e.shopBusinessId === row.shopBusinessId)
        this.shopContactsDataM = [...tmp, ...c]
        return
      }
      getShopContactByShopCode(shop.code).then(res => {
        const t = (res.data || []).map(e => {
          e.shopBusinessId = row.shopBusinessId
          e.isMdm = true
          return e
        })
        this.shopContactsDataM = [...tmp, ...t]
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.template-down{
    // display: flex;
    // align-content: center;
    display: inline-block;
    cursor: pointer;
    &>*{
      margin-right: 10px;
      color: #333;
      font-weight: 600;
    }
}
</style>
